import Vue from 'vue';
import store from '@/store';
import router from '@/router';
import toTree from './js/arrayToTree';
const _$sec = 'aAbBcdefgC#DEFGHIJKLMNOPQRSTUVWXYZ';

//将数组转化为tree
export function arrayToTree(data, options = {}) {
  return toTree(data, options);
}
export function addComponentToBody({
  className = 'demo-component',
  component = null,
  props = {},
  refName = 'demoRef',
  provide = {},
}) {
  const div = document.createElement('div');
  if (className) {
    div.setAttribute('class', className);
    const oldEl = document.querySelector(`.${className}`);
    oldEl && oldEl.remove();
  }
  document.querySelector('.bs-render-wrap').appendChild(div);
  const modelVm = Vue.extend({
    provide: {
      $store: store,
      $router: router,
      ...provide,
    },
    render(h) {
      return h(
        'div',
        {
          class: {
            [className]: true,
          },
          style: {
            transform: `perspective(500px) skew(0deg, 0deg) rotateX(0deg) rotateY(0deg) rotateZ(0deg);display:block;`,
          },
        },
        [h(component, { props, ref: refName })],
      );
    },
  });
  const vm = new modelVm();
  vm.$mount(div);
  return vm;
}

export function isTarget(e, className = 'setting-container', count = 10) {
  let status = 'start';
  let num = 0;
  let el = e.target;
  while (
    status === 'start' &&
    el.classList &&
    !el.classList.contains(className)
  ) {
    el = el.parentNode;
    num++;
    if (num >= count || !el) {
      status = 'end';
      return false;
    }
    if (el?.classList && el.classList.contains(className)) {
      return true;
    }
  }
}
export function uid() {
  var time = Date.now().toString(36);
  var random = Math.random().toString(36);
  random = random.substring(2, random.length);
  return random + time;
}
// 获取文本宽度
export function getTextWidth({
  text = 'hello world',
  size = 12,
  weight = 400,
}) {
  const font = ` ${weight} ${size}px arial`;
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  context.font = font;
  const { width } = context.measureText(text);
  return width;
}
// rgba 转化为 16 进制颜色
export function rgbToHex(color) {
  const values = color
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',');
  const a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
  return (
    '#' +
    ('0' + r.toString(16)).slice(-2) +
    ('0' + g.toString(16)).slice(-2) +
    ('0' + b.toString(16)).slice(-2)
  );
}
//16 进制颜色转化为 rgba
export const hexToRgba = (hex = '', opacity = 1) => {
  if (!hex) return '';
  if (~hex.indexOf('rgb')) {
    hex = rgbToHex(hex);
  }
  return (
    'rgba(' +
    parseInt('0x' + hex.slice(1, 3)) +
    ',' +
    parseInt('0x' + hex.slice(3, 5)) +
    ',' +
    parseInt('0x' + hex.slice(5, 7)) +
    ',' +
    opacity +
    ')'
  );
};
// 获取渐变色
export function getColorStep(color = '') {
  const [a, b, c] = color
    .split(' ')
    .filter(item => item)
    .map(v => {
      const [, color] = v.split(':');
      return color && color !== 'null' ? color : 'transparent';
    });
  return [a, b, c];
}

// 颜色兼容
export function compatibleColor(color) {
  if (typeof color === 'string') {
    const [a, b, c] = getColorStep(color);
    return [
      {
        _id: uid(),
        colors: [
          {
            step: 0,
            color: b,
          },
          {
            step: 1,
            color: c,
          },
        ],
      },
    ];
  } else {
    return color;
  }
}
// 判断背景类型
export function getBgType(color) {
  color = color + '';
  if (!color || color === 'null' || color === 'undefined') {
    return {
      type: 'color',
      color: 'rgba(255,255,255,0)',
    };
  }
  if (/\d\:/g.test(color)) {
    // 渐变颜色
    return {
      type: 'gradient',
      color: getColorStep(color),
    };
  } else if (~color.indexOf('#') || ~color.indexOf('rgb')) {
    // 普通颜色
    return {
      type: 'color',
      color,
    };
  } else if (~color.indexOf('http') || ~color.indexOf('data:image')) {
    // 图片背景
    return {
      type: 'image',
      color,
    };
  }
}
// 背景处理
export function getRealBackGround(colorType) {
  let headerClsBg = '';
  const { type, color } = getBgType(colorType);
  if (type === 'color') {
    headerClsBg = color;
  } else if (type === 'image') {
    headerClsBg = `url(${color}) no-repeat center center / 100% 100%`;
  } else if (type === 'gradient') {
    const [a, b, c] = color;
    headerClsBg = `linear-gradient(to right, ${b}, ${c})`;
  }
  return headerClsBg;
}
// 计算最小值和最大的差值
export function expandScope(a, status = 'min', rate = 0) {
  if (isNaN(a)) return 0;
  a = parseFloat(a);
  if (status === 'min') {
    return a > 0 ? a - a * rate : a + a * rate;
  } else {
    return a > 0 ? a + a * rate : a - a * rate;
  }
}

export function getSearch(url) {
  var params = {};
  let search = url ? url.split('?')[1] : window.location.search;
  if (!search) return {};
  search
    .replace('?', '')
    .split('&')
    .forEach(function (param) {
      let paramParts = param.split('=');
      params[paramParts[0]] = paramParts[1];
    });
  return params;
}

export function execFun({
  filed = 'data',
  script = '',
  params = {},
  isSync = false,
  callback = null,
}) {
  if (isSync) {
    // 支持异步函数
    try {
      const fun = new Function(filed, `return async ()=>{${script}}`);
      const res = fun(params)().then(data => {
        callback && callback(data);
      });
      return res;
    } catch (error) {
      console.warn(error);
    }
  } else {
    // 同步函数
    try {
      const res = new Function(filed, `${script}`)(params);
      callback && callback(res);
      return res;
    } catch (error) {
      console.warn(error);
    }
  }
}

// 加密
export function toEncryp(str) {
  str = encodeURIComponent(str);
  let len = _$sec.length;
  let a = _$sec.split('');
  let s = '',
    b,
    b1,
    b2,
    b3;
  for (let i = 0; i < str.length; i++) {
    b = str.charCodeAt(i);
    b1 = b % len;
    b = (b - b1) / len;
    b2 = b % len;
    b = (b - b2) / len;
    b3 = b % len;
    s += a[b3] + a[b2] + a[b1];
  }
  return s;
}
